package com.hzcx.app.simplechat.ui.moment.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.hzcx.app.simplechat.R;
import com.hzcx.app.simplechat.base.BaseFragment;
import com.hzcx.app.simplechat.bean.UpLoadImgBean;
import com.hzcx.app.simplechat.common.Common;
import com.hzcx.app.simplechat.event.ImageViewerEvent;
import com.hzcx.app.simplechat.ui.friend.event.DeleteFriendEvent;
import com.hzcx.app.simplechat.ui.main.event.NewMomentMsgEvent;
import com.hzcx.app.simplechat.ui.mine.event.RefreshUserEvent;
import com.hzcx.app.simplechat.ui.moment.MomentCreateActivity;
import com.hzcx.app.simplechat.ui.moment.MomentInfoActivity;
import com.hzcx.app.simplechat.ui.moment.NewMessageActivity;
import com.hzcx.app.simplechat.ui.moment.adapter.MomentAdapter;
import com.hzcx.app.simplechat.ui.moment.bean.MomentBean;
import com.hzcx.app.simplechat.ui.moment.bean.MomentDyImagesBean;
import com.hzcx.app.simplechat.ui.moment.bean.NewMessageCountBean;
import com.hzcx.app.simplechat.ui.moment.contract.MomentContract;
import com.hzcx.app.simplechat.ui.moment.event.DeleteCommentEvent;
import com.hzcx.app.simplechat.ui.moment.event.DeleteMomentEvent;
import com.hzcx.app.simplechat.ui.moment.event.MomentCreateEvent;
import com.hzcx.app.simplechat.ui.moment.presenter.MomentPresenter;
import com.hzcx.app.simplechat.ui.publicui.PublicRoundDialog;
import com.hzcx.app.simplechat.ui.publicui.WebViewActivity;
import com.hzcx.app.simplechat.ui.setting.ReportActivity;
import com.hzcx.app.simplechat.ui.user.UserInfoActivity;
import com.hzcx.app.simplechat.ui.user.bean.UserInfoBean;
import com.hzcx.app.simplechat.ui.user.enums.SexEnum;
import com.hzcx.app.simplechat.ui.user.event.UserRemarkEvent;
import com.hzcx.app.simplechat.util.UserInfoUtil;
import com.hzcx.app.simplechat.util.dp.DpUtils;
import com.hzcx.app.simplechat.util.empty.EmptyUtils;
import com.hzcx.app.simplechat.util.glide.GlideUtils;
import com.hzcx.app.simplechat.util.log.LogUtils;
import com.hzcx.app.simplechat.util.photo.PhotoUtil;
import com.hzcx.app.simplechat.util.video.ScrollCalculatorHelper;
import com.hzcx.app.simplechat.view.imageview.RoundImageView;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.listener.OnResultCallbackListener;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.litepal.LitePal;
import org.litepal.crud.callback.FindMultiCallback;
import org.litepal.crud.callback.SaveCallback;
import org.litepal.crud.callback.UpdateOrDeleteCallback;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 动态-列表
 */
public class MomentFragment extends BaseFragment<MomentPresenter> implements MomentAdapter.OnItemClickCallback, OnResultCallbackListener<LocalMedia>,
        BaseQuickAdapter.OnItemClickListener, BaseQuickAdapter.OnItemChildClickListener, OnRefreshListener, BaseQuickAdapter.RequestLoadMoreListener,
        MomentContract.View {


    @BindView(R.id.rv_moment)
    RecyclerView rvMoment;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.smart_refresh)
    SmartRefreshLayout smartRefresh;
    @BindView(R.id.iv_create_moment)
    ImageView ivCreateMoment;
    @BindView(R.id.view_top)
    View viewTop;
    @BindView(R.id.ll_null)
    LinearLayout llNull;
    private List<MomentBean> momentData;
    private MomentAdapter momentAdapter;

    private int scrollY = 0;
    private int scrollHeight; // 透明度变化，距离顶部的高度
    private View headerView;

    private ImageView iv_moment_bg;// 背景墙
    private RoundImageView iv_head; // 头像
    private TextView tv_nick_name;
    private ImageView iv_sex;
    private TextView tv_sign;
    private TextView tv_new_msg;

    private int page = 1;
    private boolean isRefresh = true;

    //控制滚动播放
    private ScrollCalculatorHelper scrollCalculatorHelper;
    private LinearLayoutManager linearLayoutManager;


    @Override
    public int getLayout() {
        return R.layout.fragment_moment;
    }

    @Override
    public void initPresenter() {
        mPresenter = new MomentPresenter();
    }

    @Override
    public void initView() {
        momentData = new ArrayList<>();
        momentAdapter = new MomentAdapter(momentData);
        linearLayoutManager = new LinearLayoutManager(getActivity(), RecyclerView.VERTICAL, false);
        rvMoment.setLayoutManager(linearLayoutManager);
        rvMoment.setAdapter(momentAdapter);

        momentAdapter.setOnItemClickCallback(this);
        momentAdapter.setOnItemClickListener(this);
        momentAdapter.setOnItemChildClickListener(this);

        // 设置背景先透明
        viewTop.getBackground().mutate().setAlpha(0);

        scrollHeight = DpUtils.dp2px(getActivity(), 110);

        smartRefresh.setOnRefreshListener(this);
        momentAdapter.setOnLoadMoreListener(this);
    }

    @Override
    public void initData() {

        addHeaderView();

        // 设置滑动监听，计算距离
        rvMoment.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                scorllTopView(dy);
            }
        });

        mPresenter.getNewMessageCount(getActivity());

        // 从缓存拿动态数据
        LitePal.findAllAsync(MomentBean.class, true).listen(list -> {
            if (list != null && list.size() > 0) {
                LogUtils.d(new Gson().toJson(list));
                momentData.clear();
                momentData.addAll(list);
                momentAdapter.notifyDataSetChanged();
                llNull.setVisibility(View.GONE);
            }
            // 从缓存拿到数据后，还是要更新最新的数据
            page = 1;
            isRefresh = true;
            momentAdapter.setEnableLoadMore(true);
            mPresenter.getMomentList(getActivity(), page);
        });

        //设置滑动监听
        //获取屏幕宽高
        DisplayMetrics dm = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        //自定播放帮助类 限定范围为屏幕一半的上下偏移180   括号里不用在意 因为是一个item一个屏幕
        scrollCalculatorHelper = new ScrollCalculatorHelper(R.id.videoPlayer
                , dm.heightPixels / 2 - DpUtils.dip2px(getActivity(), 300)
                , dm.heightPixels / 2 + DpUtils.dip2px(getActivity(), 300));
        rvMoment.addOnScrollListener(new RecyclerView.OnScrollListener() {
            //第一个可见视图,最后一个可见视图
            int firstVisibleItem, lastVisibleItem;

            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

                //如果newState的状态==RecyclerView.SCROLL_STATE_IDLE;
                //播放对应的视频
                scrollCalculatorHelper.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                firstVisibleItem = linearLayoutManager.findFirstVisibleItemPosition();
                lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();
                //一屏幕显示一个item 所以固定1
                //实时获取设置 当前显示的GSYBaseVideoPlayer的下标
                scrollCalculatorHelper.onScroll(recyclerView, firstVisibleItem, lastVisibleItem, lastVisibleItem - firstVisibleItem);
            }
        });
    }


    /**
     * 顶部标题透明度变化
     */
    private void scorllTopView(int dy) {
        scrollY += dy;
        int alpha = scrollY - scrollHeight;
        if (alpha <= 0) {
            alpha = 0;
        }
        if (scrollY - scrollHeight <= 255 && scrollY - scrollHeight >= 0) {
            // 先把顶部标题及按钮透明度消减为0
            tvTitle.setTextColor(Color.argb(255 - alpha, 255, 255, 255));
            ivCreateMoment.setImageAlpha(255 - alpha);
            ivCreateMoment.setImageResource(R.mipmap.ic_icon_moment_create_white);
        } else if (scrollY - scrollHeight > 255) {
            // 顶部标题及按钮已经透明，改为黑色，并且逐渐显示头部背景
            tvTitle.setTextColor(getActivity().getResources().getColor(R.color.color_282F3E));
            ivCreateMoment.setImageResource(R.mipmap.ic_icon_moment_create_black);
            int num = alpha - 255;
            if (num >= 255) {
                num = 255;
            }
            tvTitle.setTextColor(Color.argb(num, 40, 47, 62));
            ivCreateMoment.setImageAlpha(num);
            viewTop.getBackground().mutate().setAlpha(num);
        } else {
            // 表示在最上面了，直接设置成初始状态
            tvTitle.setTextColor(getResources().getColor(R.color.color_white));
            ivCreateMoment.setImageResource(R.mipmap.ic_icon_moment_create_white);
            tvTitle.setAlpha(1f);
            ivCreateMoment.setImageAlpha(255);
            viewTop.getBackground().mutate().setAlpha(0);
        }
    }

    /**
     * 查看大图
     *
     * @param position
     * @param list
     * @param viewGroup
     */
    @Override
    public void onItemClick(int position, List<String> list, ViewGroup viewGroup) {
        EventBus.getDefault().post(new ImageViewerEvent(position, viewGroup, list, momentData.get(position).getMember_id()));
    }

    /**
     * 添加头部布局
     */
    private void addHeaderView() {
        headerView = LayoutInflater.from(getActivity()).inflate(R.layout.layout_moment_header, null);
        iv_moment_bg = headerView.findViewById(R.id.iv_moment_bg);
        iv_head = headerView.findViewById(R.id.iv_head);
        tv_nick_name = headerView.findViewById(R.id.tv_nick_name);
        iv_sex = headerView.findViewById(R.id.iv_sex);
        tv_sign = headerView.findViewById(R.id.tv_sign);
        tv_new_msg = headerView.findViewById(R.id.tv_new_msg);
        iv_moment_bg.setOnClickListener(view -> showPhotoDialog());

        tv_new_msg.setOnClickListener(view -> {
            tv_new_msg.setText("0条新消息");
            startActivity(new Intent(getActivity(), NewMessageActivity.class));
        });

        momentAdapter.addHeaderView(headerView);
        momentAdapter.notifyDataSetChanged();

        loadUser();
    }

    /**
     * 刷新用户资料
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void reFreshUser(RefreshUserEvent event) {
        loadUser();
    }

    /**
     * 设置自己的用户信息
     */
    private void loadUser() {
        GlideUtils.loadImg(getActivity(), UserInfoUtil.getUserHead(), iv_head);
        tv_nick_name.setText(UserInfoUtil.getUserNickName());
        if (UserInfoUtil.getUserSex().equals(SexEnum.SEX_GRIL)) {
            iv_sex.setImageResource(R.mipmap.ic_icon_sex_gril);
            iv_sex.setVisibility(View.VISIBLE);
        } else if (UserInfoUtil.getUserSex().equals(SexEnum.SEX_BOY)) {
            iv_sex.setImageResource(R.mipmap.ic_icon_sex_boy);
            iv_sex.setVisibility(View.VISIBLE);
        } else {
            iv_sex.setVisibility(View.GONE);
        }
        tv_sign.setText(UserInfoUtil.getUserSign());
        if (EmptyUtils.isNotEmpty(UserInfoUtil.getUserBackgroundImg())) {
            GlideUtils.loadImgAsCenter(getActivity(), UserInfoUtil.getUserBackgroundImg(), iv_moment_bg);
        }
    }

    @OnClick({R.id.tv_title, R.id.iv_create_moment})
    public void viewOnClick(View view) {
        switch (view.getId()) {
            case R.id.iv_create_moment: // 发布动态
                startActivity(new Intent(getActivity(), MomentCreateActivity.class));
                break;
        }
    }

    /**
     * 封面选择
     */
    private void showPhotoDialog() {
        List<String> str = new ArrayList<>();
        str.add("从相册选取");
        str.add("拍照");
        PublicRoundDialog roundDialog = new PublicRoundDialog(getActivity(), str, (pos, menu) -> {
            switch (menu) {
                case "从相册选取":
                    PhotoUtil.showPhotoByHead(getActivity(), this);
                    break;

                case "拍照":
                    PhotoUtil.showCameraByHead(getActivity(), this);
                    break;
            }
        });
        roundDialog.show();
    }

    /**
     * 选取照片返回
     *
     * @param result
     */
    @Override
    public void onResult(List<LocalMedia> result) {
        mPresenter.upLoadImg(getActivity(), PhotoUtil.getPath(result.get(0)));
    }

    @Override
    public void onCancel() {

    }

    /**
     * 列表点击
     *
     * @param adapter
     * @param view
     * @param position
     */
    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        startActivity(new Intent(getActivity(), MomentInfoActivity.class)
                .putExtra(MomentInfoActivity.INTENT_MOMENT_ID, momentData.get(position).getDynamic_id()));
    }

    /**
     * 子控件点击
     *
     * @param adapter
     * @param view
     * @param position
     */
    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        switch (view.getId()) {
            case R.id.iv_head: // 用户头像
                startActivity(new Intent(getActivity(), UserInfoActivity.class)
                        .putExtra(UserInfoActivity.INTENT_USER_ID, momentData.get(position).getMember_id()));
                break;

            case R.id.tv_fabulous: // 点赞
                mPresenter.momentFabulous(getActivity(), momentData.get(position).getDynamic_id(), position);
                break;

            case R.id.tv_commont: // 评论
                startActivity(new Intent(getActivity(), MomentInfoActivity.class)
                        .putExtra(MomentInfoActivity.INTENT_MOMENT_ID, momentData.get(position).getDynamic_id()));
                break;

            case R.id.iv_more: // 更多按钮
                showMoreDialog(position);
                break;

            case R.id.tv_content:// 文本点击
                if (EmptyUtils.isNotEmpty(momentData.get(position).getLinkurl())) {
                    startActivity(new Intent(getActivity(), WebViewActivity.class)
                            .putExtra(WebViewActivity.INTENT_WEB_URL, momentData.get(position).getLinkurl()));
                } else {
                    startActivity(new Intent(getActivity(), MomentInfoActivity.class)
                            .putExtra(MomentInfoActivity.INTENT_MOMENT_ID, momentData.get(position).getDynamic_id()));
                }
                break;

            case R.id.tv_web_url: // 广告链接
                startActivity(new Intent(getActivity(), WebViewActivity.class)
                        .putExtra(WebViewActivity.INTENT_WEB_URL, momentData.get(position).getAd_url()));
                break;
        }
    }

    /**
     * 点击列表更多选项
     *
     * @param pos
     */
    private void showMoreDialog(int pos) {
        List<String> str = new ArrayList<>();
        if (momentData.get(pos).getMember_id() == UserInfoUtil.getUserId()) {
            // 操作自己的动态
            str.add("删除动态");
        } else {
            // 操作别人的动态
            str.add("举报");
            str.add("屏蔽此动态");
        }

        PublicRoundDialog roundDialog = new PublicRoundDialog(getActivity(), "请选择", str, (pos1, menu) -> {
            switch (menu) {
                case "删除动态":
                    mPresenter.deleteMoment(getActivity(), momentData.get(pos).getDynamic_id(), pos);
                    break;

                case "举报":
                    getActivity().startActivity(new Intent(getActivity(), ReportActivity.class)
                            .putExtra(ReportActivity.INTENT_USER_ID, momentData.get(pos).getMember_id()));
                    break;

                case "屏蔽此动态":
                    mPresenter.shieldMoment(getActivity(), momentData.get(pos).getDynamic_id(), pos);
                    break;
            }
        });
        roundDialog.show();
    }

    /**
     * 加载更多
     */
    @Override
    public void onLoadMoreRequested() {
        page++;
        isRefresh = false;
        mPresenter.getMomentList(getActivity(), page);
    }

    /**
     * 刷新
     *
     * @param refreshLayout
     */
    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        page = 1;
        isRefresh = true;
        momentAdapter.setEnableLoadMore(true);
        mPresenter.getMomentList(getActivity(), page);
        mPresenter.getNewMessageCount(getActivity());
    }

    /**
     * 数据获取成功
     *
     * @param data
     */
    @Override
    public void momentResult(List<MomentBean> data) {
        smartRefresh.finishRefresh();
        momentAdapter.loadMoreComplete();
        try {
            if (isRefresh) {
                momentData.clear();
                saveMomentDb(data);
            }
            momentData.addAll(data);
            if (data.size() < Common.PAGE_COUNT) {
                momentAdapter.loadMoreEnd();
            }
            momentAdapter.notifyDataSetChanged();
            if (momentData != null && momentData.size() > 0) {
                llNull.setVisibility(View.GONE);
            } else {
                llNull.setVisibility(View.VISIBLE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 保存缓存数据
     */
    private void saveMomentDb(List<MomentBean> data) {
        if (data != null && data.size() > 0) {
            // 如果是刷新，则缓存一下最新的数据
            LitePal.deleteAllAsync(MomentBean.class).listen(rowsAffected -> {
                // 删除本地数据成功，保存这次获取的所有数据
                for (int i = 0; i < data.size(); i++) {
                    data.get(i).save();
                    if (data.get(i).getDy_images() == null || data.get(i).getDy_images().size() <= 0) {
                        continue;
                    }
                    for (int j = 0; j < data.get(i).getDy_images().size(); j++) {
                        data.get(i).getDy_images().get(j).save();
                    }
                }
                LogUtils.d("缓存数据保存成功");
            });
        }
    }

    /**
     * 加载失败
     */
    @Override
    public void onFail() {
        smartRefresh.finishRefresh();
        momentAdapter.loadMoreFail();
    }

    /**
     * 图片上传成功
     *
     * @param data
     */
    @Override
    public void upLoadImgResult(UpLoadImgBean data) {
        mPresenter.updateBackImg(getActivity(), data.getUrl());
    }

    /**
     * 背景墙修改成功
     *
     * @param url
     */
    @Override
    public void updateBackImgSuccess(String url) {
        try {
            UserInfoBean bean = UserInfoUtil.getUserInfo();
            bean.setBackimage(url);
            UserInfoUtil.saveUser(bean);
            loadUser();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 点赞成功
     */
    @Override
    public void fabulousSuccess(int pos) {
        if (momentData.get(pos).getGreatstate() == 0) {
            momentData.get(pos).setGreatstate(1);
            momentData.get(pos).setGreatcount(momentData.get(pos).getGreatcount() + 1);
        } else {
            momentData.get(pos).setGreatstate(0);
            momentData.get(pos).setGreatcount(momentData.get(pos).getGreatcount() - 1);
        }
        momentAdapter.notifyDataSetChanged();
    }

    /**
     * 动态删除成功
     */
    @Override
    public void deleteSuccess(int pos) {
        momentData.remove(pos);
        momentAdapter.notifyDataSetChanged();
        showError("删除成功");
        if (momentData != null && momentData.size() > 0) {
            llNull.setVisibility(View.GONE);
        } else {
            llNull.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 新消息条数获取成功
     *
     * @param data
     */
    @Override
    public void newMsgResult(NewMessageCountBean data) {
        tv_new_msg.setText(data.getNews_count() + "条新消息");
        if (data.getNews_count() > 0) {
            tv_new_msg.setVisibility(View.VISIBLE);
        } else {
            tv_new_msg.setVisibility(View.GONE);
        }
    }

    /**
     * 动态屏蔽成功
     *
     * @param pos
     */
    @Override
    public void shieldSuccess(int pos) {
        momentData.remove(pos);
        momentAdapter.notifyDataSetChanged();
        showError("屏蔽成功");
    }

    /**
     * 其他页面删除动态成功
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void momentDeleteSuccess(DeleteMomentEvent event) {
        for (int i = 0; i < momentData.size(); i++) {
            if (momentData.get(i).getDynamic_id() == event.getId()) {
                momentData.remove(i);
            }
        }
        momentAdapter.notifyDataSetChanged();
    }

    /**
     * 动态发布成功
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void momentCreateSuccess(MomentCreateEvent event) {
        smartRefresh.autoRefresh();
    }

    /**
     * 评论删除成功
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void commentDeleteSuccess(DeleteCommentEvent event) {
        for (int i = 0; i < momentData.size(); i++) {
            if (momentData.get(i).getDynamic_id() == event.getId()) {
                momentData.get(i).setReviewcount(momentData.get(i).getReviewcount() - 1);
            }
        }
        momentAdapter.notifyDataSetChanged();
    }


    /**
     * 删除好友成功,需要删除相对应的好友动态
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void deleteFriendSuccess(DeleteFriendEvent event) {
        smartRefresh.autoRefresh();
    }

    /**
     * 用户备注名设置成功，更新列表相对应的昵称
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void setRemarkNameSuccess(UserRemarkEvent event) {
        for (int i = 0; i < momentData.size(); i++) {
            if (momentData.get(i).getMember_id() == event.getBean().getMember_id()) {
                momentData.get(i).setNickname(event.getBean().getRemarks_name());
            }
        }
        momentAdapter.notifyDataSetChanged();
    }

    /**
     * 动态有新消息
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void newMessageCount(NewMomentMsgEvent event) {
        if (event.getCount() <= 0) {
            return;
        }
        tv_new_msg.setText(event.getCount() + "条新消息");
    }

}
